How to drag a captionless form in free pascal-lazarus-typhon

Drag Captionless

We are going to create a demonstration on how to make a captionless form that can be dragged by pulling from any place from its form. Some ideas were borrowed from this site http://delphi.about.com/library/weekly/aa102505a.htm  and http://lazplanet.blogspot.com.uy/2013/06/dragging-form-by-its-body.html

Create a new project in its own new directory and call it dragcaptionless Unit.

Add a TButton to the lower right part of the newly created form. Change Caption property to ‘Bye!’.

Form1

On the OnClick Event Handler write the following code:

procedure TForm1.Button1Click(Sender: TObject);
begin
 Application.Terminate;
end;

We add the following variables to the private part of TForm1. These will save the Form’s position while moving it.

private
  { private declarations }
  //Variables to keep form position
  inReposition : boolean;
  oldPos : TPoint; 
public

At the uses clause, add the LCLIntf Library like the following:

uses
 Classes, ...   ...,
 // Compatibility library gives SetCapture and ReleaseCapture
 LCLIntf;

Now select the form Form1 on the Designer window.

On Form1.OnCreate Event Handler add the following code:

procedure TForm1.FormCreate(Sender: TObject);
begin
 self.BorderIcons:=[];
 self.BorderStyle:=bsNone;
end;

This turns off the border and caption from our form.

On Form1.OnMouseDown Event Handler add the following code:

procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
 Shift: TShiftState; X, Y: Integer);
begin
 if (Sender is TForm) then
 begin
   //Get the MouseDown cursor position and keep it
   oldPos.X:=X;
   oldPos.Y:=Y;
   //we are now repositioning the form
   inReposition:=True;
 end;
end;

This code sets the beginning of the moving procedure for the form.

On Form1.OnMouseMove Event Handler add the following code:

procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
 Y: Integer);
var
 newPos: TPoint;
begin
 // Get actual position from mouse for this event
 newPos.X:=X;
 newPos.Y:=Y;
 //if we are moving
 if inReposition then
 begin
 with TForm(Sender) do
 begin
 //Change cursor to grab mode
 Screen.Cursor := crSize;
 //Adjust new form position relative to first position
 SetBounds(Left + (newPos.X - oldPos.X), Top + (newPos.Y - oldPos.Y), Width, Height);
 end;
 end;
end;

This will change the form’s position while moving.

On Form1.OnMouseUp Event Handler add the following code:

procedure TForm1.FormMouseUp(Sender: TObject; Button: TMouseButton;
 Shift: TShiftState; X, Y: Integer);
begin
 if inReposition then
 begin
 //Restore normal cursor
 Screen.Cursor := crDefault;
 //We are not moving anymore
 inReposition := False;
 end;
end;

This restores the cursor and stops moving the form.

Now we are ready to compile and run.

Run | Build

and (if it did not retrieve errors)

Run | Run

And drag it around!

Regards!

Related posts